package com.mayikt.weixin.mp.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mayikt.base.BaseResponse;
import com.mayikt.constants.Constants;
import com.mayikt.member.output.dto.UserOutDTO;
import com.mayikt.utils.HttpClientUtils;
import com.mayikt.utils.RedisUtils;
import com.mayikt.utils.RegexUtils;
import com.mayikt.weixin.feign.MemberServiceFeign;
import com.mayikt.weixin.mp.builder.TextBuilder;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired

    private MemberServiceFeign memberServiceFeign;

    @Value("${mayikt.weixin.registration.code.message}")
    private String registrationMessage;

    @Value("${mayikt.weixin.default.registration.code.message}")
    private String defaultMessage;


//    @Value("${redis.host}")
//    private String redisHost;
//
//    @Value("${redis.password}")
//    private String redisPassword;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }

        //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                    && weixinService.getKefuService().kfOnlineList()
                    .getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                        .fromUser(wxMessage.getToUser())
                        .toUser(wxMessage.getFromUser()).build();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }


        //String content = "收到信息内容：" + JsonUtils.toJson(wxMessage);
        String fromContent = wxMessage.getContent();
        String toContent = "";
        if (RegexUtils.checkMobile(fromContent)) {

            BaseResponse<UserOutDTO> resultUserInfo = memberServiceFeign.existMobile(fromContent);

            if (resultUserInfo.getCode().equals(Constants.HTTP_RES_CODE_200)) {
                toContent = "该手机号码" + fromContent + "已经存在";
                return new TextBuilder().build(toContent, wxMessage, weixinService);
            }
            if (!resultUserInfo.getCode().equals(Constants.EXISTMOBILE_CODE_203)) {
                toContent = "该手机号码" + fromContent + "已经存在";
                return new TextBuilder().build(resultUserInfo.getMsg(), wxMessage, weixinService);
            }
            int code = registrationCode();
            toContent = String.format(registrationMessage, code);
            //将注册码存入redis
            redisUtils.set(Constants.WEIXINCODE_KEY + "_" + fromContent, String.valueOf(code), Constants.WEIXINCODE_TIME);
        } else {
            //微信机器人
            toContent = HttpClientUtils.doGet("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + fromContent);
            JSONArray jsonArray = JSONArray.parseArray("[" + toContent + "]");
            for (Object object : jsonArray) {
                JSONObject jsonObject = (JSONObject) object;
                String content = jsonObject.getString("content");
                toContent = content.replace("{br}", "\n");
            }

        }
        //return new TextBuilder().build(toContent+"   redis host："+redisHost+"redis pwd："+redisPassword, wxMessage, weixinService);
        return new TextBuilder().build(toContent, wxMessage, weixinService);
    }

    private int registrationCode() {

        return (int) (Math.random() * 9999 + 1000);
    }

}
